<script lang="ts" setup>
  import { ref } from "vue"
  import gmDialog from '@/components/Dialog/index.vue'
  import { getAllMenu } from '@/api/menu'
  import { saveOrUpdate, getRoleById } from '@/api/role'
  import { type FormInstance, type FormRules, ElMessage,ElTree } from "element-plus"
  import * as instance from '@/api/role/types/instance'
  import {type menuRowFormInstance} from '@/api/menu/types/instance'

  interface Props {
    id ?: number
  }
  const rules: FormRules = {
    name: [
      { required: true, message: '请输入角色名称', trigger: 'blur' },
    ],
    code: [
      { required: true, message: '请输入角色编码', trigger: 'blur' },
    ]
  }

  const props = withDefaults(defineProps<Props>(), {
    id: 0,
  })

  const form = ref<instance.roleFormInstance>({
    status: 0
  })
  const loading = ref(true)
  const formRef = ref<FormInstance>()
  const treeRef = ref<InstanceType<typeof ElTree>>()
  const menuList = ref<Array<menuRowFormInstance>>([])
  const menuListObject = ref<any>({})
  const defaultChecked = ref<Array<number>>([])
  const dialogRef = ref<InstanceType<typeof gmDialog>>()
  const emit = defineEmits(['cancel','success'])

  const cancel = () => {
    emit('cancel')
  }

  const getMenu = () => {
    getAllMenu({type:2}).then((res: any)=>{
      menuList.value = res
      setDataObj(res)
    })
  }

  const setDataObj = (list: any) => {
    list.forEach((item: any)=>{
      menuListObject.value[item.menuId] = item
      if(item.childrenList && item.childrenList.length) {
        setDataObj(item.childrenList)
      }
    })
  }

  const getDetail = () => {
    getRoleById({id:props.id}).then((res: any)=>{
      form.value = res
      defaultChecked.value = res.permissions.map((item)=>item.menuId)
      loading.value = false
    })
  }

  const success =  async(formEl: FormInstance | undefined)=>{
    dialogRef.value.setLoading(true)
    await formEl?.validate((valid) => {
      if (!valid) {
        dialogRef.value.setLoading(false)
        return
      }
      const addList:Array<number> = []
      const checkList = treeRef.value.getCheckedNodes()

      function checkAddOParent (row: any) {
      console.log(row,'row')
        if(row.parentId && !addList.includes(row.parentId)) {
          addList.push(row.parentId)
          console.log(menuListObject.value[row.parentId],'menuListObject.value[row.parentId]')
          checkAddOParent(menuListObject.value[row.parentId])
        }
      }

      checkList.forEach((item)=>{
        addList.push(item.menuId)
        checkAddOParent(item)
      })
      form.value.role = addList.map((item)=>{
        return {
          id: item,
        }
      })
      saveOrUpdate(form.value).then(()=>{
         ElMessage({
            message: '操作成功',
            type: 'success',
          })
        emit('success')
      }).catch(()=>{
        dialogRef.value.setLoading(false)
      })
    })
  }

  getMenu()
  if(props.id) getDetail()

</script>

<template>
  <gm-dialog
    ref="dialogRef"
    :title="!form.roleId ? '新增角色' : '修改角色'"
    @cancel="cancel"
    @comfirm="success(formRef)"
    v-loading="loading">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" label-position="left">
      <el-form-item prop="name" label="角色名">
        <el-input v-model="form.name" placeholder="" />
      </el-form-item>
      <el-form-item prop="code" label="角色编码">
        <el-input v-model="form.code" placeholder="" />
      </el-form-item>
      <el-form-item prop="permissions" label="权限">
        <el-scrollbar >
          <el-tree
            :data="menuList"
            show-checkbox
            node-key="menuId"
            ref="treeRef"
            :default-checked-keys="defaultChecked"
            :props="{
              children: 'childs',
              label: 'name',
              value: 'menuId',
            }"
          />
        </el-scrollbar>
      </el-form-item>
      <el-form-item prop="code" label="状态">
        <el-radio-group v-model="form.status">
          <el-radio-button label="启用" :value="0" />
          <el-radio-button label="停用" :value="1" />
        </el-radio-group>
      </el-form-item>
    </el-form>
  </gm-dialog>
</template>


<style lang="scss" scoped>
:deep(.el-input__wrapper) {
  .el-icon{
    color:#333;
    font-size:20px;
  }
}
:deep(.el-scrollbar){
  width: 100%;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  height:250px;
}
</style>
